package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {


    @Autowired
    private StrategyThemeRepository strategyThemeRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void insert(StrategyTheme strategyTheme) {
        strategyThemeRepository.insert(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        //orElse方法从optional中取值，如果取不到返回null
        return strategyThemeRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return strategyThemeRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
//        //原始代码
//        Query query = new Query();
//        long totalcount = mongoTemplate.count(query, StrategyTheme.class);
//        if(totalcount == 0){
//            //没有数据
//            return Page.empty();
//        }
//        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
//        query.with(pageable);
//        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);
//        Page<StrategyTheme> page =  new PageImpl<>(list, pageable, totalcount);
//        return page;
        return DBHelper.query(mongoTemplate, StrategyTheme.class, qo, null);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        System.out.println(strategyTheme.getId());
        if(!StringUtils.hasLength(strategyTheme.getId())){
            //防止id为空串，直接写入到数据库，导致自动生成_id不成功
            strategyTheme.setId(null);
            strategyThemeRepository.save(strategyTheme);
        }
        else{
            strategyThemeRepository.save(strategyTheme);
        }
    }

}
